package com.wondersgroup.app.appointment.controller;

import java.util.HashMap;
import java.util.List;
import java.util.Map;

import javax.servlet.http.HttpServletRequest;
import javax.servlet.http.HttpServletResponse;

import org.springframework.beans.factory.annotation.Autowired;
import org.springframework.security.web.csrf.CsrfToken;
import org.springframework.stereotype.Controller;
import org.springframework.web.bind.annotation.RequestMapping;
import org.springframework.web.bind.annotation.RequestMethod;
import org.springframework.web.bind.annotation.ResponseBody;

import com.wondersgroup.core.frame.BaseController;
import com.wondersgroup.core.frame.CommonStatusResult;
import com.wondersgroup.core.model.AppVersion;
import com.wondersgroup.core.model.Attachment;
import com.wondersgroup.core.resultmap.DTOAppVersion;
import com.wondersgroup.core.service.AppVersionService;
import com.wondersgroup.core.service.UtilService;
import com.wondersgroup.core.util.ErrorMessageConstant;
import com.wondersgroup.core.util.QueryResult;
import com.wondersgroup.core.util.TraceConstant;

@Controller
@RequestMapping("/system")
public class SystemController extends BaseController{

	@Autowired
	private AppVersionService appVersionService;
	@Autowired
	private UtilService utilService;
	@RequestMapping(value ="/upgrade",method = RequestMethod.GET)
	@ResponseBody
	public CommonStatusResult upgrade() throws Exception{
		Map<String,String> map = new HashMap<String, String>();
		QueryResult<DTOAppVersion> resultA=appVersionService.searchApplicationVersion(AppVersion.APP_TYPE_ANDROID,  1, null, null, null, null, 1, 10);
		if(resultA!=null && resultA.getResultList()!=null && resultA.getResultList().size()>0){
			DTOAppVersion appVer=resultA.getResultList().get(0);
			int appId = appVer.getId();
			//附件
			Attachment attachment = new Attachment();
			attachment.setObjType(TraceConstant.ATT_APP);
			attachment.setObjId(appId);
			List<Attachment> apks = utilService.queryAttFile(attachment);
			if(apks!=null&&apks.size()>0){
				map.put("appVer", String.valueOf(appVer.getAppVer()));
				map.put("filePath",apks.get(0).getFilePath());
				map.put("appVersionName", appVer.getVersionName());
			}
		}
		return CommonStatusResult.success(ErrorMessageConstant.CODE_SUCCESS, map);
	}
	
	@RequestMapping(value ="/token",method = RequestMethod.GET)
	@ResponseBody
	public CommonStatusResult token(HttpServletRequest request,HttpServletResponse response) {
		CsrfToken token = (CsrfToken)request.getAttribute("_csrf");
		Map result = new HashMap();
		result.put("key", token.getHeaderName());
		result.put("value", token.getToken());
		return CommonStatusResult.success(ErrorMessageConstant.CODE_SUCCESS, result);
	}
}
